package com.smile.cloud.order.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 延时生产者
 *
 * @author LGC
 */
@Slf4j
@Component
public class DelayProducer {

    public final static String DELAY_TRANS_GROUP = "delay_trans_group";
    public final static String TOPIC_ORDER_DELAY = "order_delay";
    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        log.info(DELAY_TRANS_GROUP + " producer 正在创建---------------------------------------");
        producer = new DefaultMQProducer(DELAY_TRANS_GROUP);
        producer.setNamesrvAddr("127.0.0.1:9876");
        producer.setSendMsgTimeout(Integer.MAX_VALUE);
        this.start();
    }

    private void start() {
        try {
            this.producer.start();
            log.info(DELAY_TRANS_GROUP + " producer server 开启成功----------------------------------");
        } catch (MQClientException e) {
            log.info(DELAY_TRANS_GROUP + " producer server 开启异常：{0}----------------------------------", e);
        }
    }

    public SendResult send(String data, String topic, int level) throws Exception {
        Message message = new Message(topic, data.getBytes());
        //1s，5s，10s，30s，1m，2m，3m，4m，5m，6m，7m，8m，9m，10m，20m，30m，1h，2h。
        //level=0，表示不延时。level=1，表示 1 级延时，对应延时 1s。level=2 表示 2 级延时，对应5s，以此类推
        message.setDelayTimeLevel(level);
        return this.producer.send(message);
    }

    public SendResult send(String data, String topic, String tags, int level) throws Exception {
        Message message = new Message(topic, tags, data.getBytes());
        message.setDelayTimeLevel(level);
        return this.producer.send(message);
    }
}
